/**
 * Created by root on 5/23/16.
 */

var remove_id = function (id, reload) {
    $("#" + id).remove();
    if (reload) {
        location.reload();
    }
};

var error_dialog = function () {
    this.show = function (_title, _description, timeout) {
        var content = "<div id='id_error_message_dialog' style='position: absolute; z-index:100000; background-color:red; height:80px;left: 5%; width: 90%; margin-top: 20px;'><div style='position:relative; margin-left: 40px; margin-top: 10px;'><span style='color:white; font-weight: bold'>" + _title + "</span></div><div style='position: relative; margin-left:40px; margin-top: 10px;'><span style='color:white'>" + _description + "</span></div><div ></div></div>";
        $('#body:first').prepend(content);
        setTimeout("remove_id('id_error_message_dialog', true)", timeout);
    };
};


function upload_file(div, name) {
    var input = '<input type="file" class="form-control" name="' + name + '">';
    var div_obj = $("#" + div);
    div_obj.children().remove();
    div_obj.append(input);
}

function html5Reader(file, pic) {
    // var file = file.files[0];
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (e) {
        pic.src = this.result;
    }
}


function clear_input_file(id_input_file) {
    var oldInput = document.getElementById(id_input_file);

    var newInput = document.createElement("input");

    newInput.type = "file";
    newInput.id = oldInput.id;
    newInput.name = oldInput.name;
    newInput.className = oldInput.className;
    newInput.style.cssText = oldInput.style.cssText;
    newInput.onchange = oldInput.onchange;
    newInput.onclick = oldInput.onclick;
    // copy any other relevant attributes

    oldInput.parentNode.replaceChild(newInput, oldInput);
}

function upload_image(input_id, img_id, width, height) {
    var pic = document.getElementById(img_id),
        file = document.getElementById(input_id);

    // var ext = file.value.substring(file.value.lastIndexOf(".") + 1).toLowerCase();
    //
    // if (ext != 'png' && ext != 'jpg' && ext != 'jpeg') {
    //     alert("图片的格式必须为png或者jpg或者jpeg格式！请重新上传。");
    //     clear_input_file(input_id);
    //     if (pic) {
    //         pic.src = "";
    //     }
    //     return false;
    // }

    if (width || height) {
        if (file.offsetWidth > width || file.offsetHeight > height) {
            alert("图片大小不能超过" + width + "*" + height + ",请重新上传。");
            clear_input_file(input_id);
            if (pic) {
                pic.src = "";
            }
            return false;
        }
    }

    var isIE = navigator.userAgent.match(/MSIE/) != null,
        isIE6 = navigator.userAgent.match(/MSIE 6.0/) != null;

    if (isIE) {
        file.select();
        var reallocalpath = document.selection.createRange().text;

        if (isIE6) {
            pic.src = reallocalpath;
        } else {
            pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image',src=\"" + reallocalpath + "\")";
            // 设置img的src为base64编码的透明图片 取消显示浏览器默认图片
            pic.src = '';
        }
    } else {
        if (pic) {
            html5Reader(file.files[0], pic);
        }
    }
}

function upload_multiple_images(input_id, img_id, width, height) {
    var file = document.getElementById(input_id);

    for (var i = 0; i < file.files.length; i++) {
        var f = file.files[i];
        if (img_id) {
            var id_img = document.getElementById(img_id + i);
            if (id_img != null) {
                html5Reader(f, id_img);
            }
        }
    }
}

function to_id(prefix, bits, d) {
    var id = d.toString();
    var len = id.length;

    if (len < bits) {
        for (var i = 0; i < bits - len; i++) {
            id = '0' + id;
        }
    }

    return prefix + id;
}

// 验证返回值
function validate_return(data) {
    if (data['status'] == 'ErrOk') {
        return true;
    } else {
        alert(data['message'] + "[errcode:" + data['status'] + ']');
        return false;
    }
}

// // 显示模态对话框
function show_modal_dialog(div) {
    var bg = document.getElementById('id_dialog_background');
    if (bg == null) {
        var bg = $('<div class="dialog_bg" id="id_dialog_background"></div>');
        bg.append(div);
    }
    $('body').prepend(bg);
}

function close_modal_dialog() {
    $('#id_dialog_background').remove();
}

function show_error_message(name, message)
{
    var err_id=name+"-error";
    var err_obj = $("#"+err_id);
    var obj = $("input[name='"+name+"']");

    if (obj == null) {
        return;
    }

    if (!err_obj.length) {
        err_obj = $('<label id="'+err_id+'" class="error" for="'+name+'"></label>');
        err_obj.insertAfter(obj);
    }
    err_obj.text(message);
}

function validate_form_ex(form, data)
{
    var rules = data['rules'];
    var messages = data['messages'];
    $(".error").remove();

    for (var name in rules) {
        if (!rules.hasOwnProperty(name)) {
            continue;
        }

        var r = rules[name];
        var msgs = messages[name];
        var obj = $('#'+form+' [name="'+name+'"]');

        if (!obj.length) {
            return false;
        }

        if (r.hasOwnProperty('required') && r.required && obj.val().length <= 0) {
            show_error_message(name, msgs.required);
            return false;
        }

        if (r.hasOwnProperty('minLength') && obj.val().length < r.minLength) {
            show_error_message(name, msgs.minLength);
            return false;
        }

        if (r.hasOwnProperty('maxLength') && obj.val().length > r.maxLength) {
            show_error_message(name, msgs.maxLength);
            return false;
        }

        if (r.hasOwnProperty('equalTo') && obj.val() != r.equalTo.val()) {
            show_error_message(name, msgs.equalTo);
            return false;
        }
    }

    return true;
}